/**
 * Created by Administrator on 2015/9/8.
 * 公式编辑页面
 * @options.aFormData 编辑的字段集合
 * @options.infoSetId 信息集id
 * @options.oTableList 表格列表对象
 */
define(function(require, exports, module) {
    var template = require("commonStaticDirectory/plugins/template");  //载入一些要依赖的模块
    //ztree
    require("commonStaticDirectory/plugins/zTree/zTreeStyle/zTreeStyle.css");
    require("commonStaticDirectory/plugins/zTree/jquery.ztree.all.min");

    //弹窗组件
    require("commonStaticDirectory/plugins/artDialog/ui-dialog.css"); //artDialog弹窗
    require("commonStaticDirectory/plugins/artDialog/dialog-plus.js");
    //ajax
    var Ajax = require("commonStaticDirectory/plugins/ajax.js");

    require("commonStaticDirectory/plugins/autoForm/autoForm.css");
    var AutoForm = require("commonStaticDirectory/plugins/autoForm/autoForm.js");//自动化表单组件

    var sFormulaEdit = require("commonStaticDirectory/plugins/fromula/templateFormulaEdit.js"); //模板
    require("commonStaticDirectory/plugins/fromula/fromula.css"); //样式

    require("commonStaticDirectory/plugins/jquery.loading.js"); //loading遮罩插件
    //下拉框
    require("commonStaticDirectory/plugins/dayhrDropSelect/dayhrDropSelect.css");
    var DayhrDropSelect = require("commonStaticDirectory/plugins/dayhrDropSelect/dayhrDropSelect.js");
    var tools = require("commonStaticDirectory/plugins/tools.js");
    require("commonStaticDirectory/plugins/underscore.min.js");
    require("commonStaticDirectory/plugins/jquery.loading.js");

    //表单验证
    require('commonStaticDirectory/plugins/jquery.validator/local/zh_CN');

    //kindeditor编辑器
    require("commonStaticDirectory/plugins/kindeditor/themes/default/default.css");
    require("commonStaticDirectory/plugins/kindeditor/kindeditor.all.min.js");



    var DialogFromulaEdit = function(){
        this.init.apply(this,arguments);
    }
    DialogFromulaEdit.prototype = {
        constructor : DialogFromulaEdit
        ,defaultOptions:{
            isEdit:true
        }
        /**
         *初始化函数
         */
        ,init : function(options){
            var t = this;
            t.options= $.extend({}, t.defaultOptions,options);
            //加载完成关闭loading
            if(t.options.oLayer){
                layer.close(t.options.oLayer);//关闭loading遮罩
            }
            //这里是所以弄成全局变量是为了让百度编辑器的插件中也能读取并设置这些变量，用到的地方：添加到编辑区、智能分析
            window.dayhrFormula = {
                ue_cl:["如果", "那么", "再滤", "其余", "并且", "或者","同时"]
                ,colors:{DEFAULT: "black", ITEM: "red", PROP: "blue", LOGIC: "green", FUNC: "#04B4AE","null":null}
                ,ue_items:{}
                ,ue_ci:undefined
                ,ue_cp:undefined  //带中括号的[员工姓名]，暂时不用
                ,ue_cf:undefined  //函数
            };

            t.oRenderData = {};
            if(t.options.aFormData && t.options.aFormData.length){
                for(var i=0;i< t.options.aFormData.length;i++){
                    t.oRenderData[t.options.aFormData[i].name] = (t.options.aFormData[i].value || t.options.aFormData[i].value == 0)?t.options.aFormData[i].value:"";
                }
            }

            t.initDialog(t.oRenderData); //初始化弹窗
            t.initLeftTree(); //加载左侧树
            t.initOtherPlugins(); //加载其他表单插件
            t.initEditor(); //初始化编辑器
        }
        /**
         * 初始化弹窗
         * */
        ,initDialog:function(oRenderData){
            var t = this;
            t.layerIndex1 = layer.open({
                type: 1
                ,title:"计算公式"
                ,content:template.compile(sFormulaEdit)(oRenderData)
                ,area: ['1000px']
                ,maxmin: true
                ,zIndex:99999
                ,end:function(){
                    //关闭弹窗就销毁编辑器
                }
                //最大化的回调事件
                ,full:function(){
                    $(".layui-layer-content").css({height:"100%"});
                    $("#formula_tree").css({height:$(window).height() - 160 + "px"});  //窗口的高度 - 弹窗除了树标题的其他地方的高度
                    $("#formula_right").css({height:"auto"});
                    t.editor.edit.setHeight($(window).height() - 360);//设置编辑器的高度为 窗口的高度 - 原来除了编辑器的其他地方的高度
                }
                //还原的回调事件
                ,restore:function(){
                    $(".layui-layer-content").css({height:"580px"});
                    $("#formula_tree").css({height:"442px"});
                    $("#formula_right").css({height:"500px"});
                    t.editor.edit.setHeight(250);
                }
            });
        }
        /**
         * 加载左侧树
         * */
        ,initLeftTree:function(){
            var t = this;
            //初始化基础树
            t.baseSetting = {
                callback : {
                    onDblClick : function(event, treeId, treeNode){
                        if (treeNode && treeNode.isParent){
                            return;
                        }
                        treeNode && t.insertAtCaret(treeNode.name, window.dayhrFormula.colors.ITEM);
                    }
                }
            };
            $.fn.zTree.init($("#formula_tree"), t.baseSetting, []);

            t.getBaseTreeNodesData(function(aNodes){
                if(aNodes && $.isArray(aNodes) && aNodes.length){
                    var aNames = [];
                    var fnLoopNodes = function(arr){
                        for(var i=0;i<arr.length;i++){
                            aNames.push(arr[i].name);
                            window.dayhrFormula.ue_items[arr[i].name] = "["+arr[i].data.set_id+"."+arr[i].id+"]";
                            if(arr[i].children && arr[i].children.length){
                                fnLoopNodes(arr[i].children);
                            }
                        }
                    }
                    fnLoopNodes(aNodes);
                    window.dayhrFormula.ue_ci = aNames;

                    $.fn.zTree.init($("#formula_tree"), t.baseSetting, aNodes);
                }
            });
        }
        /**
         * 获取基本的树节点
         * */
        ,getBaseTreeNodesData:function(callback){
            var t = this;
            if(t.options.oTableList.baseFormulaTreeData){
                typeof callback == "function" && callback(t.options.oTableList.baseFormulaTreeData);
            }else{
                //获取树的新节点
                Ajax.ajax({
                    url:gMain.basePath +"formulaInfoSet/getinfoitem.do",
                    data:JSON.stringify(t.options.data.getinfoitem),
                    beforeSend:function(){
                        $("#formula_left").loading(); //遮罩树
                    },
                    complete:function(){
                        $("#formula_left").loading({state:false}); //遮罩树
                    },
                    success: function(data){
                        if(data.result == "true"){
                            if(data.infoitem && $.isArray(data.infoitem) && data.infoitem.length){
                                var aNodes = t.formatToZtreeData(data.infoitem,false);
                                t.options.oTableList.baseFormulaTreeData = aNodes; //缓存到oTableList上,方便下次点击弹出直接获取
                                typeof callback == "function" && callback(aNodes);
                            }
                        }
                    }
                });
            }
        }
        /**
         * 加载其他表单插件
         * */
        ,initOtherPlugins:function(){
            var t = this;
            //下拉框
            Ajax.ApiTools().getKeyValueData({
                data:{"corpId":null,"infoSetId":"ct_094","conditionId":null,"keyId":"code_id","valueId":"code_name","tipId":null,"parentId":null,"conditionBean":null,"conditionFieldId":null,"isDateFilter":false,"orderBean":null,"orderStr":null}
                ,beforSend:function(){
                    $("#formula_edit_wrap").loading();
                }
                ,complate:function(){
                    $("#formula_edit_wrap").loading({state:false});
                }
                ,success:function(data){
                    if(data.beans && $.isArray(data.beans) && data.beans.length){
                        var oDropOptions = {
                            id:"formula_Group_drop"
                            ,width:130
                            ,maxHeight: 250
                            ,data: data.beans
                            ,name: "precision"
                        };
                        var formGroup = new DayhrDropSelect(oDropOptions);
                        if(t.oRenderData && t.oRenderData.pre){
                            formGroup.setValue(t.oRenderData.pre); //编辑的时候设置值
                        }else{
                            formGroup.setValue("2");
                        }
                    }
                }
            });

            //是否控件
            $("#formula_query").find(".switch-checkbox").bootstrapSwitch();

            //公式说明的选项卡切换
            $(".formula_dec_wrap").on("click","dt>span",function(){
                var iIndex =  $(this).index();
                $(this).addClass("on").siblings().removeClass("on");
                $(".formula_dec_wrap").find("dd>.dd_div").eq(iIndex).show().siblings().hide();
            });

            //保存按钮的点击
            $("#formula_buttons_ok").on("click",function(){
                var aDataList = [];//提交的字段的集合
                if(!$.trim($("#formulaName").val())){
                    layer.msg("公式名称不能为空", {offset: 0,shift:6});
                    $("#formulaName").focus();
                    return false;
                }else{
                    aDataList.push({
                        key:"name"
                        ,value:$.trim($("#formulaName").val())
                    });
                }

                if(!t.options.data.getinfoitem.type){
                    layer.msg("公式分组不能为空", {offset: 0,shift:6});
                    return false;
                }else{
                    aDataList.push({
                        key:"type"
                        ,value:t.options.data.getinfoitem.type
                    });
                }

                if(!t.editor.text()){
                    layer.msg("公式内容不能为空", {offset: 0,shift:6});
                    t.editor.focus(); //获取焦点
                    return false;
                }else{
                    aDataList.push({
                        key:"content"
                        ,value: t.editor.text().replace(/&gt;/g,">").replace(/&lt;/g,"<")
                    });
                    aDataList.push({
                        key:"htmlContent"
                        ,value: t.editor.html()
                    });
                    aDataList.push({
                        key:"express"
                        ,value: t.formulaParser(t.editor.text().replace(/&gt;/g,">").replace(/&lt;/g,"<"))
                    });
                }

                //显示顺序
                aDataList.push({
                    key:"sortsn"
                    ,value:$("#formulaOrder").val()
                });
                //是否运算
                aDataList.push({
                    key:"iscal"
                    ,value:$("#formulaCalculate").prop("checked")?1:0
                });
                //描述
                aDataList.push({
                    key:"remark"
                    ,value: $.trim($("#formula_dec").val())
                });
                //精度
                aDataList.push({
                    key:"pre"
                    ,value: $.trim($("#formula_Group_drop").find("input[name='precision']").val())
                });

                //如果是编辑就移除那些没有改变的字段，如果是公式分组字段就一定提交，如果是内容和表达式也一定要提交
                if(t.options.saveType == "edit"){
                    var aDataListEdit = [];
                    for(var i=0;i<aDataList.length;i++){
                        if(t.oRenderData[aDataList[i].key] != aDataList[i].value || aDataList[i].key == "type"|| aDataList[i].key == "content"|| aDataList[i].key == "express"){
                            aDataListEdit.push(aDataList[i]);
                        }
                    }
                    aDataList = aDataListEdit;
                }

                var oSubmitData = {dataList:aDataList,infoSetId: t.options.infoSetId};
                if(t.options.saveType == "edit"){
                    oSubmitData.uuid = t.options.uuid;
                }

                //如果是新增，rule_id:111
                if(t.options.saveType == "add"){
                    aDataList.push({
                        key:"rule_id"
                        ,value: t.options.data.insert.rule_id
                    });
                }

                //如果没有被修改的项就直接提示保存成功
                if(t.options.saveType == "edit" && !oSubmitData.dataList.length){
                    layer.msg("保存成功", {offset: 0});
                    t.layerIndex1 && layer.close(t.layerIndex1);
                }else{
                    Ajax.ajax({
                        url:gMain.basePath+"route/"+ t.options.infoSetId+"/"+(t.options.saveType=="add"?"insert":"update")+".do",
                        data:(JSON.stringify(oSubmitData)).replace("script",""),
                        beforeSend:function(){
                            $("body").loading({zIndex:99999999});
                        }
                        ,complete:function(){
                            $("body").loading({state:false});
                        }
                        ,dataType:"json",
                        success:function(data){
                            if(data.result == "true"){
                                layer.msg("保存成功", {offset: 0});
                                if(t.layerIndex1){
                                    layer.close(t.layerIndex1);
                                }
                                t.options.oTableList.mmg.load();
                            }else if(data.result == "false"){
                                $("#formula_error").html(data.resultDesc);
                                $(".formula_dec_wrap").find(">dt>span").eq(1).addClass("on").siblings().removeClass("on");
                                $(".formula_dec_wrap").find(".dd_div").eq(1).show().siblings().hide();
                            }
                        }
                    });
                }
            });

            //取消（关闭）弹窗
            $("#formula_buttons_cancel").on("click",function(){
                t.layerIndex1 && layer.close(t.layerIndex1);
            });
        }
        /**
         * 插入节点到编辑器
         * */
        ,insertAtCaret:function(name, color, addSpace){
            var t = this;
            if (name == "◎")
                name = "\"";
            if (name == "<")
                name = "&lt;";
            if (name == ">")
                name = "&gt;";
            if (name == "<=")
                name = "&lt;=";
            if (name == ">=")
                name = "&gt;=";
            var html = "<span";
            html += " style='color: " + (color ? color : window.dayhrFormula.colors.DEFAULT) + ";'";
            html += ">";
            html += (addSpace ? "&nbsp;" : "") + name + (addSpace ? "&nbsp;" : "");
            html += "</span>";
            t.editor.insertHtml(html);
        }
        /**
         * 表达式格式化
         * */
        ,formulaParser:function(content) {
            var keys = _.keys(window.dayhrFormula.ue_items);
            keys = keys.sort(function(str1, str2) {
                return str2.length - str1.length
            });
            var regex = new RegExp(keys.join("|")
                .replace(/\]/g, "\\]").replace(/\[/g, "\\[")
                .replace(/\)/g, "\\)").replace(/\(/g, "\\("), "g");
            content = content.replace(regex, function(match, index, text) {
                if(index > 0) {
                    var c = text.charAt(index - 1);
                    if(c && c != " " && c != "+" && c != "-" && c != "*" && c != "/" && c != "="
                        && c != ">" && c != "<" && c != "(" && c != "\"" && c != "," && c != "果"
                        && c != "么" && c != "滤" && c != "余" && c != "且" && c != "者" && c != "时"){
                        return match;
                    }
                    c = text.charAt(index + match.length);
                    if(c && c != " " && c != "+" && c != "-" && c != "*" && c != "/" && c != "="
                        && c != ">" && c != "<" && c != ")" && c != "\"" && c != "," && c != "如"
                        && c != "那" && c != "再" && c != "其" && c != "并" && c != "或" && c != "同"){
                        return match;
                    }
                }
                return window.dayhrFormula.ue_items[match] + match;
            });
            return content;
        }
        /**
         * 初始化编辑器
         * */
        ,initEditor:function(){
            var t = this;
            t.editor = null;
            if(t.oRenderData && t.oRenderData.htmlContent){
                $("#formula_editor_id").val(t.oRenderData.htmlContent); //编辑的时候设置值
            }
            KindEditor.lang({
                autotool : '智能分析'
            });
            t.editor = KindEditor.create('#formula_editor_id', {
                resizeType:0,
                allowPreviewEmoticons : false,
                newlineTag:'br',
                items : [
                    'autotool','|','fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                    'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright']
                ,afterCreate:function(){
                    setTimeout(function(){
                        t.editor.focus();
                    },100);
                }
            });
            t.bindFormulaButtons(); //编辑按钮的事件绑定
        }
        /**
         * 编辑按钮的事件绑定
         */
        ,bindFormulaButtons : function(){
            var t = this;
            $("#formula_eidtor_buttons").on("click",".shrbtn-primary",function(){
                var sValue = $(this).attr("data-value");
                if(sValue){
                    sValue = sValue.replace(/\s/g,"");
                    //如果是“高级”按钮
                    if(sValue == "openSeniorWindow"){
                        t.openSeniorWindow();
                    }else{
                        if(sValue.indexOf(",") != -1){
                            var _arr = sValue.split(",");
                            t.insertAtCaret(_arr[0], window.dayhrFormula.colors[_arr[1]],_arr[2]=="true"?true:false);
                        }else{
                            t.insertAtCaret(sValue);
                        }
                    }
                }
            });
        }
        /**
         * 获取高级树
         * */
        ,getHighFormulaTreeData:function(callback,isReload){
            var t = this;
            if(t.options.oTableList.highFormulaTreeData && !isReload){
                typeof callback == "function" && callback(t.options.oTableList.highFormulaTreeData);
            }else{
                Ajax.ajax({
                    url:gMain.basePath +"formulahighgrade/gettree.do",
                    data:JSON.stringify({}),
                    beforeSend:function(){

                    },
                    complete:function(){

                    },
                    success: function(data){
                        if(data.result == "true"){
                            window.dayhrFormula.ue_cf = [];
                            var setNodesType =function(arr,sType){
                                for(var i=0;i<arr.length;i++){
                                    if(sType == "function"){
                                        window.dayhrFormula.ue_cf.push(arr[i].name);
                                    }
                                    arr[i].treeType = sType;
                                }
                            };
                            var aNodes = [];//节点
                            //函数
                            if(data.function && $.isArray(data.function) && data.function.length){
                                setNodesType(data.function,"function");
                                aNodes = aNodes.concat(t.formatToZtreeData(data.function,true));
                            }
                            //临时表
                            if(data.table && $.isArray(data.table) && data.table.length){
                                setNodesType(data.table,"table");
                                aNodes = aNodes.concat(t.formatToZtreeData(data.table,true));
                            }
                            //变量
                            if(data.var && $.isArray(data.var) && data.var.length){
                                setNodesType(data.var,"var");
                                aNodes = aNodes.concat(t.formatToZtreeData(data.var,true));
                            }

                            t.options.oTableList.highFormulaTreeData = aNodes;
                            typeof callback == "function" && callback(aNodes);
                        }
                    }
                });
            }
        }
        /**
         * 高级按钮事件
         * */
        ,openSeniorWindow:function(){
            var t = this;

            //如果是非超级管理员就隐藏操作按钮
            t.oDialog2 = dialog({
                title:"核算公式高级选项"
                ,content:'<div id="formula_high_treewrap" class="clearfix" style="width:960px;">' +
                    '<div class="l" style="float:left;">' +
                        '<div class="ztree" id="formula_high_tree" style="width: 220px;height:511px;overflow-y: scroll;overflow-x: auto;border: 1px solid #ccc;"></div>' +
                    '</div>' +
                    '<div class="r" style="border: 1px solid #ccc; width:712px; height: 500px; padding-top: 22px;">' +
                        '<div id="formula_high_edit_node" class="clearfix"></div>' +
                        '<div id="formula_high_edit_buttons" class="clearfix" style="text-align: right;padding: 10px 32px;"><input type="button" class="flat-button flat-medium flat-yellow" style="padding: 5px 16px 6px; font-size: 13px;'+(t.options.isEdit?"":"display:none;")+'" value="保存" /></div>' +
                    '<div id="formula_high_edit_tip" style="text-align: center;"></div>'+
                    '</div>' +
                '</div>'
                ,button:[
                    {
                        value: '确定',
                        callback: function () {
                            var oData = t.oHighNode || {};
                            if($.isEmptyObject(oData)){
                                return false;
                            }
                            var sFormula = oData.valueName;
                            //如果是函数
                            if (oData.data.treeType == "function") {
                                var params = oData.data.paralist ? oData.data.paralist.split(",") : [];
                                sFormula += "(";
                                for ( var i = 0; i < params.length; i++) {
                                    if (params[i].trim() == "String") {
                                        sFormula += "\"\"";
                                    }
                                    if (i < params.length - 1) {
                                        sFormula += " ,";
                                    }
                                }
                                sFormula += ")";
                            }
                            t.insertAtCaret(sFormula, oData.data.treeType == "function" ? window.dayhrFormula.colors.FUNC : window.dayhrFormula.colors.DEFAULT);
                        },
                        autofocus: true
                    },
                    {
                        value: '取消',
                        callback: function () {}
                    }
                ]
            }).showModal();


            //高级树
            t.bRemoveFlag = false; //默认点击删除不执行删除节点，而是提示下，为true才删除
            var oTreeTypeName = {"function":"函数","table":"临时表","var":"变量"};
            t.highSetting = {
                view: {
                    showIcon: true,
                    showTitle:true,
                    //用于当鼠标移动到节点上时，显示用户自定义控件，显示隐藏状态同 zTree 内部的编辑、删除按钮
                    addHoverDom:function(treeId, treeNode){
                        //禁止编辑的状态
                        if(!t.options.isEdit){
                            return;
                        }
                        var sObj = $("#" + treeNode.tId + "_span");
                        if(treeNode.data.treeType == "function" && !treeNode.getParentNode()){
                            return;
                        }else if(treeNode.data.treeType == "table" && treeNode.getParentNode()){
                            return;
                        }else if(treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0 || !treeNode.isParent){
                            return;
                        }

                        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                            + "' title='添加"+(oTreeTypeName[treeNode.data.treeType])+"' onfocus='this.blur();'></span>";
                        sObj.after(addStr);
                        var btn = $("#addBtn_"+treeNode.tId);
                        if (btn) btn.bind("click", function(){
                            if(treeNode.data.treeType == "function"){
                                t.oHighEditForm().functionForm({type:'add',treeNode:treeNode});
                            }else if(treeNode.data.treeType == "table"){
                                t.oHighEditForm().tableForm({type:'add',treeNode:treeNode});
                            }else if(treeNode.data.treeType == "var"){
                                t.oHighEditForm().varForm({type:'add',treeNode:treeNode});
                            }
                            return false;
                        });
                    },
                    //必须与addHoverDom同时使用
                    removeHoverDom: function(treeId, treeNode){
                        $("#addBtn_"+treeNode.tId).unbind().remove();
                    },
                    selectedMulti: false
                },
                edit:{
                    enable:true,
                    //显示删除按钮的条件
                    showRemoveBtn:function(treeId, treeNode) {
                        //禁止编辑的状态
                        if(!t.options.isEdit){
                            return false;
                        }
                        if(treeNode.data.treeType == "table"){
                            var sNodes = treeNode.getParentNode();
                            return (treeNode.children && treeNode.children.length > 0 && sNodes) ;
                        }
                        else{
                            return !treeNode.isParent;
                        }

                    },
                    showRenameBtn:false,
                    removeTitle:"删除"
                },
                data: {
                    key: {
                        title: "fullName"
                    }
                },
                callback : {
                    onClick : function(event, treeId, treeNode){
                        var showTemp = false;
                        if(treeNode && treeNode.data.treeType == "table"){
                            if(treeNode.getParentNode()){
                                showTemp = true;
                            }
                        }else if(treeNode && !treeNode.isParent){
                            showTemp = true;
                        }

                        var fnSetOldData = function(){
                            //把编辑前的数据缓存起来
                            t._oOldEditData = {};
                            var $form = $("#formula_high_edit_node").find(">form:first");
                            $form.find("[name]").each(function(){
                                var _key = $(this).attr("name");
                                var _value = $(this).val();
                                t._oOldEditData[_key] = _value;
                            });
                        }
                        if(showTemp){
                            //如果是函数类型
                            if(treeNode.data.treeType == "function"){
                                t.oHighEditForm().functionForm({type:'edit',treeNode:treeNode});
                                var $form = $("#formula_high_edit_node").find(">form:first");
                                $form.find("input[name='name']").val(treeNode.name);
                                $form.find("input[name='sortsn']").val(treeNode.data.sortsn);
                                $form.find("input[name='define']").val(treeNode.data.define);
                                $form.find("input[name='paralist']").val(treeNode.data.paralist); //参数列表
                                $form.find("textarea[name='content']").val(treeNode.data.content);
                                $form.find("textarea[name='remark']").val(treeNode.data.remark);

                                if(t.highFunctionForm){
                                    for(var i=0;i< t.highFunctionForm.options.data.length;i++){
                                        var _item = t.highFunctionForm.options.data[i];
                                        //类型的下拉框
                                        if(_item.name == "type"){
                                            _item.dayhrDropSelect.setValue(treeNode.data.type);
                                        }else if(_item.name == "returntype"){ //返回值的下拉框
                                            _item.dayhrDropSelect.setValue(treeNode.data.code_name);
                                        }
                                    }
                                }
                                fnSetOldData();

                            }else if(treeNode.data.treeType == "table" && treeNode.children && treeNode.children.length > 0){
                                //如果是临时表
                                t.oHighEditForm().tableForm({type:'edit',treeNode:treeNode}); //临时表编辑的表单
                                var $form = $("#formula_high_edit_node").find(">form:first");
                                $form.find("input[name='name']").val(treeNode.name.substr(treeNode.name.indexOf("]")+1));
                                $form.find("input[name='define']").val(treeNode.data.define);
                                $form.find("input[name='periodform']").val(treeNode.data.periodform);
                                $form.find("input[name='periodto']").val(treeNode.data.periodto);
                                $form.find("input[name='sortsn']").val(treeNode.data.sortsn);
                                $form.find("input[name='paraidlist']").val(treeNode.data.paraidlist);
                                $form.find("input[name='paranamelist']").val(treeNode.data.paranamelist);
                                $form.find("input[name='paratypelist']").val(treeNode.data.paratypelist);
                                $form.find("textarea[name='sqls']").val(treeNode.data.sqls);
                                $form.find("textarea[name='remark']").val(treeNode.data.remark);
                                fnSetOldData();

                            }else if(treeNode.data.treeType == "var"){
                                //如果是变量
                                t.oHighEditForm().varForm({type:'edit',treeNode:treeNode}); //变量编辑的表单
                                var $form = $("#formula_high_edit_node").find(">form:first");
                                $form.find("input[name='name']").val(treeNode.name);
                                $form.find("input[name='define']").val(treeNode.data.define);
                                $form.find("input[name='sortsn']").val(treeNode.data.sortsn);
                                $form.find("textarea[name='remark']").val(treeNode.data.remark);
                                if(t.highVarForm){
                                    for(var i=0;i< t.highVarForm.options.data.length;i++){
                                        var _item = t.highVarForm.options.data[i];
                                        //类型的下拉框
                                        if(_item.name == "type"){
                                            _item.dayhrDropSelect.setValue(treeNode.data.type);
                                        }else if(_item.name == "returntype"){ //返回值的下拉框
                                            _item.dayhrDropSelect.setValue(treeNode.data.code_name);
                                        }
                                    }
                                }
                                fnSetOldData();

                            }
                            //如果是临时表的话就选择最子集的节点，但是编辑的是文件夹
                            if(treeNode.data.treeType == "table" && treeNode.children && treeNode.children.length){
                                t.oHighNode = null; //把高级树的点击节点先缓存起来，方便点击弹窗的确定按钮的时候用
                            }else{
                                t.oHighNode = treeNode; //把高级树的点击节点先缓存起来，方便点击弹窗的确定按钮的时候用
                            }
                        }
                    },
                    //删除前
                    beforeRemove: function(treeId, treeNode){
                        var zTree = $.fn.zTree.getZTreeObj("formula_high_tree");
                        zTree.selectNode(treeNode);

                        if(!t.bRemoveFlag){
                            var oTreeType = {"function":"函数","table":"临时表","var":"变量"};
                            layer.confirm("确定要删除<span style='color: red;'>"+treeNode.name+"</span>这个<span style='color:blue;'>"+oTreeType[treeNode.data.treeType]+"</span>？", {icon: 3, title:'提示'}, function(index){
                                t.bRemoveFlag = true;
                                var sInfoSetId = '';
                                var aUuid = [];
                                if(treeNode.data.treeType == 'function'){
                                    aUuid = [treeNode.id];
                                    infoSetId = 'forfunction_list';
                                }else if(treeNode.data.treeType == "table"){
                                    aUuid = [treeNode.data.uuid];
                                    infoSetId = 'fortable_list';
                                }else if(treeNode.data.treeType == "var"){
                                    aUuid = [treeNode.id];
                                    infoSetId = 'forvar_list';
                                }
                                var aSendData = {infoSetId:infoSetId,uuidLists:aUuid};
                                Ajax.ApiTools().del({
                                    infoSetId:infoSetId
                                    ,data:aSendData
                                    ,success:function(data){
                                        if(data.result == "true"){
                                            t.options.oTableList.baseFormulaTreeData && (t.options.oTableList.baseFormulaTreeData = null);//清空缓存
                                            layer.msg("删除成功", {offset: 0});
                                            $("#"+treeNode.tId+"_remove")[0].click();
                                        }
                                    }
                                });
                                layer.close(index);
                            });
                        }
                        return t.bRemoveFlag;
                    },
                    //删除后
                    onRemove:function(event, treeId, treeNode){
                        t.bRemoveFlag = false; //恢复到默认状态
                    }
                }
            };
            $.fn.zTree.init($("#formula_high_tree"), t.highSetting, []);

            t.getHighFormulaTreeData(function(aNodes){
                $.fn.zTree.init($("#formula_high_tree"), t.highSetting, aNodes);
                t.oHighNode = null; //刚初始化树的时候清空高级树的点击节点的缓存
                $('#formula_high_edit_buttons').hide();
                $('#formula_high_edit_tip').text('函数、临时表、变量编辑区');
            });

        }
         /**
         * 创建各种修改节点的表单
         * */
        ,oHighEditForm:function(){
            var t = this;
            return {
                /**
                 * 修改函数的表单
                 * @opt.tppe 新增还是修改
                 * @opt.treeNode 当前点击的树节点
                 * */
                functionForm:function(opt){
                    var opt = opt || {};
                    $('#formula_high_edit_tip').hide();
                    $('#formula_high_edit_buttons').show();
                    //如果是超级管理员可编辑状态
                    if(t.options.isEdit){
                        t.highFunctionForm = new AutoForm({
                            id:"formula_high_edit_node",
                            data:[
                                {name:"name",label:"名称",type:"text",value:""},
                                {name:"sortsn",label:"显示顺序",type:"text",value:""},
                                {name:"define",label:"定义",type:"text",value:""},
                                {name:"type",label:"类型",type:"treeSelect",treeJsonArr:[{id:1,name:"数学函数"},{id:2,name:"字符串函数"},{id:3,name:"日期函数"},{id:4,name:"薪酬函数"}]},
                                {name:"returntype",label:"返回值类型",type:"treeSelect",treeJsonArr:[{id:1,name:"数值型"},{id:2,name:"字符型"}]},
                                {name:"paralist",label:"参数列表",type:"text",value:""},
                                {name:"content",label:"函数体",type:"textarea",value:"",height:168},
                                {name:"remark",label:"备注",type:"textarea",value:"",height:100}
                            ],
                            minHeight:50,
                            showRow:2
                        });
                    }else{
                        t.highFunctionForm = new AutoForm({
                            id:"formula_high_edit_node",
                            data:[
                                {name:"remark",label:"描述",type:"textarea",value:"",height:431}
                            ],
                            minHeight:50,
                            showRow:2
                        });
                    }

                    //如果是新增就自动选中类型
                    if(opt.type == "add"){
                        if(t.highFunctionForm){
                            for(var i=0;i< t.highFunctionForm.options.data.length;i++){
                                var _item = t.highFunctionForm.options.data[i];
                                //类型的下拉框
                                if(_item.name == "type"){
                                    _item.dayhrDropSelect.setValue(opt.treeNode.name);
                                }
                            }
                        }
                    }
                    //保存数据
                    t.saveData(opt);

                }
                //临时表的表单
                ,tableForm:function(opt){
                    $('#formula_high_edit_tip').hide();
                    $('#formula_high_edit_buttons').show();
                    //如果是超级管理员可编辑状态
                    if(t.options.isEdit){
                        t.highTableForm = new AutoForm({
                            id:"formula_high_edit_node",
                            data:[
                                {name:"name",label:"名称",type:"text",value:""},
                                {name:"define",label:"定义",type:"text",value:""},
                                {name:"periodform",label:"起始时间偏量",type:"text",value:""},
                                {name:"periodto",label:"结束时间偏量",type:"text",value:""},
                                {name:"sortsn",label:"显示顺序",type:"text",value:""},
                                {name:"paraidlist",label:"参数定义列表",type:"text",value:""},
                                {name:"paranamelist",label:"参数名称列表",type:"text",value:""},
                                {name:"paratypelist",label:"参数类型列表",type:"text",value:""},
                                {name:"sqls",label:"查询语句",type:"textarea",value:"",height:120},
                                {name:"remark",label:"描述",type:"textarea",value:"",height:100}
                            ],
                            minHeight:50,
                            showRow:2
                        });
                    }else{
                        t.highTableForm = new AutoForm({
                            id:"formula_high_edit_node",
                            data:[
                                {name:"remark",label:"描述",type:"textarea",value:"",height:431}
                            ],
                            minHeight:50,
                            showRow:2
                        });
                    }

                    //如果是新增就自动把定义加上一个前缀
                    if(opt.type == "add"){
                        $("#formula_high_edit_node").find("input[name='define']").val("TEMP_");
                    }
                    //保存数据
                    t.saveData(opt);
                }
                //变量的表单
                ,varForm:function(opt){
                    $('#formula_high_edit_tip').hide();
                    $('#formula_high_edit_buttons').show();

                    //如果是超级管理员可编辑状态
                    if(t.options.isEdit){
                        t.highVarForm = new AutoForm({
                            id:"formula_high_edit_node",
                            data:[
                                {name:"name",label:"名称",type:"text",value:""},
                                {name:"define",label:"定义",type:"text",value:""},
                                {name:"sortsn",label:"显示顺序",type:"text",value:""},
                                {name:"type",label:"返回值类型",type:"treeSelect",treeJsonArr:[{id:1,name:"数值型"},{id:2,name:"字符型"}]},
                                {name:"remark",label:"描述",type:"textarea",value:"",height:330}

                            ],
                            minHeight:50,
                            showRow:2
                        });
                    }else{ //否则
                        t.highVarForm = new AutoForm({
                            id:"formula_high_edit_node",
                            data:[
                                {name:"remark",label:"描述",type:"textarea",value:"",height:431}
                            ],
                            minHeight:50,
                            showRow:2
                        });
                    }

                    //保存数据
                    t.saveData(opt);
                }
            };
        }
        /*
        * 保存数据
        * @opt.type add||eidt
        * @opt.treeNode 当前树节点
        * */
        ,saveData:function(opt){
            var opt = opt || {}; //参数
            var t = this;
            //把编辑前的数据缓存起来
            var $form = $("#formula_high_edit_node").find(">form:first");
            var oFields = {};
            var oTip = {
                rule: 'required;',
                msg: {
                    required: "此项不能为空！"
                }
            }
            $form.find("[name]").each(function(){
                var _key = $(this).attr("name");
                oFields[_key] = oTip;
            });

            var aUuid = [];
            var infoSetId ='';

            var sActionStr = opt.type=="add"?"新增":"修改";

            $form.validator({
                theme: "yellow_right",
                timely:1, //在失去焦点时验证
                stopOnError:true,
                //自定义用于当前实例的消息
                fields:oFields
                ,valid:function(form) {
                    var treeNode = opt.treeNode;
                    if(treeNode.data.treeType == 'function'){
                        aUuid = [treeNode.id];
                        infoSetId = 'forfunction_list';
                    }else if(treeNode.data.treeType == "table"){
                        aUuid = [treeNode.data.uuid];
                        infoSetId = 'fortable_list';
                    }else if(treeNode.data.treeType == "var"){
                        aUuid = [treeNode.id];
                        infoSetId = 'forvar_list';
                    }
                    var oSubmitData = {dataList:[],infoSetId:infoSetId};
                    $form.find("[name]").each(function(){
                        var _key = $(this).attr("name");
                        var _value = $(this).val();
                        //如果是checkbox表单
                        if($(this).attr("type") == "checkbox"){
                            if($(this).prop("checked")){
                                _value = 1;
                            }else{
                                _value = 0;
                            }
                        }
                        //如果是日历表单
                        if(_value == "" && opt.type == "edit"){
                            if(_key == "date_from"){
                                _value = "1900-01-01";
                            }else if(_key == "date_to"){
                                _value = "2099-12-31";
                            }
                        }
                        //新增的时候如果该表单项有值才提交
                        if(opt.type =="add"){
                            if($(this).val()){
                                oSubmitData.dataList.push({key:_key,value:_value});
                            }
                        }else if(opt.type =="edit" && !$.isEmptyObject(t._oOldEditData)){ //如果是编辑的时候，如果数据没修改就不提交
                            for(var i in t._oOldEditData){
                                if(i ==_key && _value !=t._oOldEditData[i]){
                                    oSubmitData.dataList.push({key:_key,value:_value});
                                }
                            }
                        }

                    });
                    //如果是编辑
                    if(opt.type=="edit"){
                        oSubmitData.uuid = aUuid[0];
                        if(!oSubmitData.dataList.length){
                            layer.msg(sActionStr+"成功", {offset: 0}); //成功提示弹层
                            return false;
                        }
                    }
                    var pageLayer = layer.load(1, {shade: [0.3,'#ffffff']}); //启用loading遮罩
                    Ajax.ajax({
                        url:gMain.basePath+(opt.type=="add"?"route/"+ oSubmitData.infoSetId +"/insert.do":"route/"+ oSubmitData.infoSetId+"/update.do"),
                        data:JSON.stringify(oSubmitData),
                        dataType:"json",
                        success:function(data){
                            layer.close(pageLayer);//关闭loading遮罩
                            if(data.result =="true"){
                                t.options.oTableList.baseFormulaTreeData && (t.options.oTableList.baseFormulaTreeData = null);//清空缓存
                                layer.msg(sActionStr+"成功", {offset: 0}); //成功提示弹层
                                t.getHighFormulaTreeData(function(aNodes){
                                    $.fn.zTree.init($("#formula_high_tree"), t.highSetting, aNodes);
                                    t.oHighNode = null; //刚初始化树的时候清空高级树的点击节点的缓存
                                },true);
                            }
                        }
                    });
                }
            });
            $('#formula_high_edit_buttons').off("click").on("click","input[type='button']",function(){
                $form.trigger("validate");
            });
        }
         /**
         * 将数组格式化成ztree需要的数据，原理遍历两次搞定，第一次把数组的每个元素和数组中的各个元素都进行pid的比较，第二次遍历为找到全部的一级父节点即可
         * @arr 要进行格式化的数组
         * */
        ,formatToZtreeData:function(arr,isOpenFirstNode){
            var aNewArr = [];//新数组,一级节点为全部的pId为null的
            if($.isArray(arr) && arr.length){
                for(var i=0;i<arr.length;i++){
                    for(var j=0;j<arr.length;j++){
                        if(arr[i].pId == arr[j].id){
                            var aChildren = arr[j].children || [];
                            var _obj = {
                                id:arr[i].id
                                ,name:arr[i].name //要显示在树上的值
                                ,valueName:arr[i].name //拿来取的值
                                ,fullName:arr[i].name //显示的值
                                ,children:arr[i].children
                            };
                            if(arr[i].treeType == "table"){
                                _obj.name = arr[i].name.substr(arr[i].name.indexOf("]")+1);
                            }
                            //把其他数据放到树节点的data对象中
                            var tempObj = _.clone(arr[i]);
                            delete tempObj.id;
                            delete tempObj.name;
                            delete tempObj.children;
                            _obj.data = tempObj;
                            aChildren.push(_obj);
                            arr[j].children = aChildren;
                        }
                    }
                }
                //再遍历一次一级节点
                for(var i=0;i<arr.length;i++){
                    if(!arr[i].pId){
                        var _obj = {
                            id:arr[i].id
                            ,name:arr[i].name  //要显示在树上的值
                            ,valueName:arr[i].name  //拿来取的值
                            ,fullName:arr[i].name //显示的值
                            ,open:isOpenFirstNode?true:false
                            ,children:arr[i].children
                        };
                        if(arr[i].treeType == "function"){
                            _obj.icon = gMain.basePath+"static/base/images/fromula/function.jpg";
                        }else if(arr[i].treeType == "table"){
                            _obj.icon = gMain.basePath+"static/base/images/fromula/table.jpg";
                        }else if(arr[i].treeType == "var"){
                            _obj.icon = gMain.basePath+"static/base/images/fromula/var.jpg";
                        }
                        //把其他数据放到树节点的data对象中
                        var tempObj = _.clone(arr[i]);
                        delete tempObj.id;
                        delete tempObj.name;
                        delete tempObj.children;
                        _obj.data = tempObj;
                        aNewArr.push(_obj);
                    }
                }
            }
            return aNewArr;
        }
    };
    module.exports = DialogFromulaEdit;
});
